<template>
  <div class="container">
    <div class="app-container">
      <div>
        <el-button type="primary" size="small" @click="isShow = true">添加角色</el-button>
      </div>
      <!-- <hr> -->
      <br>
      <div>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="角色" width="120" align="center">
            <template #default="obj">
              <div>
                <el-form v-if="obj.row.isEdit" ref="formNameRef" :model="obj.row.temp" :rules="rules" size="small">
                  <el-form-item prop="name">
                    <el-input v-model="obj.row.temp.name" />
                  </el-form-item>
                </el-form>
                <span v-else>{{ obj.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="启用" width="100" align="center">
            <template #default="obj">
              <div>
                <el-form v-if="obj.row.isEdit" :model="obj.row.temp" :rules="rules" size="small">
                  <el-form-item label="" prop="state">
                    <el-switch
                      v-model="obj.row.temp.state"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-form>
                <span v-else>
                  {{ obj.row.state === 1 ? '启用' : '禁用' }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述">
            <template #default="obj">
              <div>
                <el-form v-if="obj.row.isEdit" ref="formDescriptionRef" :model="obj.row.temp" :rules="rules" size="small">
                  <el-form-item label="" prop="description">
                    <el-input v-model="obj.row.temp.description" type="textarea" :rows="2" />
                  </el-form-item>
                </el-form>
                <span v-else>{{ obj.row.description }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="obj">
              <div v-if="obj.row.isEdit">
                <el-button type="primary" size="mini" @click="saveEdit(obj.row)">确定</el-button>
                <el-button type="danger" size="mini" @click="cancelEdit(obj.row)">取消</el-button>
              </div>
              <div v-else style="display: flex; align-items: center;justify-content: space-evenly;">
                <el-button size="mini" type="text" @click="openPermission(obj.row)">分配权限</el-button>
                <el-button size="mini" type="text" style="margin-left: 0px;" @click="editRole(obj.row)">编辑</el-button>
                <el-popconfirm
                  title="确定删除吗？"
                  @onConfirm="deleteRole(obj.row.id)"
                >
                  <template #reference>
                    <el-button size="mini" type="text">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <br>
      <!-- 分页 -->
      <div style="display: flex; justify-content: center;">
        <el-pagination
          :page-size="config.pagesize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="config.total"
          :page-sizes="[2, 5, 6, 7, 8]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <!-- 新增角色的对话框 -->
      <el-dialog title="新增角色" :visible.sync="isShow" append-to-body destroy-on-close @close="clearForm">
        <el-form ref="formRef" :model="form" label-width="100px" :rules="rules" size="small">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch
              v-model="form.state"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="addRole">确定</el-button>
          <el-button @click="isShow = false">取消</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的对话框 -->
      <el-dialog title="分配权限" :visible.sync="isPermission" append-to-body destroy-on-close @close="closePermission">
        <el-tree
          ref="tree"
          show-checkbox
          default-expand-all
          node-key="id"
          :data="treeData"
          :props="defaultProps"
          :default-checked-keys="rolePermission"
        />
        <template #footer>
          <el-button type="primary" @click="savePermission">确定</el-button>
          <el-button @click="closePermission">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoleList, deleteRole, addRole, getRoleDetail, assignPermissions, updateRole } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { convert2Tree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      treeData: [],
      config: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      isEdit: false, // 编辑角色
      editId: -1, // 编辑角色id
      isShow: false, // 新增角色
      isPermission: false, // 分配权限
      form: {
        name: '',
        state: 0,
        description: ''
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rolePermission: [], // 角色权限点
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
          // 不做，因为没有完整的数据
          // { validator: (rule, value, callback) => {
          //   const a = this.tableData.filter(item => !item.isEdit).some(item => item.name === value)
          //   if (a) {
          //     callback(new Error('角色名称已存在'))
          //   }
          //   callback()
          // }, message: '', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 编辑角色
    editRole(row) {
      // 方式一
      // this.isEdit = true
      // this.editId = row.id
      // 方式二
      this.$set(row, 'temp', { ...row })
      row.isEdit = true
    },
    // 保存编辑
    async saveEdit(row) {
      console.log(row)
      // const a = this.$refs.formNameRef.validate()
      // console.log(a)
      Promise.all([
        this.$refs.formNameRef.validate(),
        this.$refs.formDescriptionRef.validate()
      ]).then(async([a, b]) => {
        if (a && b) {
          await this.updateRole(row)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 更新角色
    async updateRole(row) {
      try {
        await updateRole(row.temp)
        this.$message.success('更新角色成功')
        this.cancelEdit(row)
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    // 取消编辑
    cancelEdit(row) {
      row.isEdit = false
      this.clearForm()
    },
    async deleteRole(id) {
      console.log(id)
      await deleteRole(id)
      // 给提示
      this.$message.success('删除角色成功')
      // 如果页面只有一条数据，将page-1
      if (this.tableData.length === 1 && this.config.page > 1) {
        this.config.page--
      }
      this.getRoleList()
    },

    // 获取角色列表
    async getRoleList() {
      const res = await getRoleList(this.config)
      this.tableData = res.rows
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false) // 设置每个item的isEdit为false, 数据响应式
      })
      this.config.total = res.total
      const totalPage = Math.ceil(this.config.total / this.config.pagesize)
      if (totalPage < this.config.page && totalPage > 0) {
        this.config.page = totalPage
      }
      // 给提示
      // this.$message.success('获取角色列表成功')
    },
    // 分页中页码变化触发的函数
    handleCurrentChange(page) {
      console.log(page)
      this.config.page = page
      this.getRoleList()
    },
    // 分页中每页显示的条数变化触发的函数
    handleSizeChange(size) {
      console.log(size)
      this.config.pagesize = size
      this.config.page = 1 // 重置页码，防止分页超过最大页码
      this.getRoleList()
    },
    async addRole() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          await addRole(this.form)
          this.$message.success('新增角色成功')
          this.isShow = false
          this.getRoleList()
        }
      })
    },
    // 清空表单
    clearForm() {
      this.form = {
        name: '',
        state: 0,
        description: ''
      }
    },
    // 打开分配权限
    async openPermission(row) {
      try {
        await Promise.allSettled([
          this.getPermissionList(),
          this.getRoleDetail(row.id)
        ])
        this.isPermission = true
        this.rolePermission = this.form.permIds
      } catch (error) {
        console.log(error)
      }
      this.isPermission = true
      this.rolePermission = this.form.permIds
    },
    // 获取角色详情
    async getRoleDetail(id) {
      const res = await getRoleDetail(id)
      this.form = res
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.treeData = convert2Tree(res)
    },
    // 关闭权限对话框
    closePermission() {
      this.isPermission = false
      this.rolePermission = []
      this.treeData = []
      this.clearForm()
    },
    // 保存权限
    async savePermission() {
      // console.log(this.rolePermission)
      const res = this.$refs.tree.getCheckedKeys()
      // console.log(res)
      await assignPermissions(this.form.id, res)
      this.$message.success('分配权限成功')
      this.closePermission()
      // this.getRoleList()
    }
  }
}
</script>
<style scoped>
  .app-container {
    padding: 30px 140px;
    font-size: 14px;
  }
</style>
